<template>
  <div class="page-common-layout">
    <div class="page-common-left" style="width:15%;padding: 0">
      <TableClassify
        :title="classifyTitle"
        :treeData="classifyData"
        @select="masterRowClick"
        :replaceFields="{ title: 'classificationName', key: 'uuid' }"
        :loading="masterConfirmLoading"
        searchPlaceholder="接口分类"
        searchFieldName="classificationName"
      ></TableClassify>
    </div>
    <div class="page-common-content">
      <tool-bar @search="$refs.subList.refresh(true)" @reset="resetSearchForm">
        <template slot="toolBtn" slot-scope="scope">
          <a-button
            class="cu-btn-primary"
            icon="plus"
            @click="openCardSelection('add', '选择接口类型')"
            >新建
          </a-button>
          <a-button icon="upload" type="link" @click="importReportFile"
            >导入</a-button
          >
        </template>
        <template slot="toolForm">
          <a-form-item label="接口名称">
            <a-input
              v-model="subQueryParam.interfaceName"
              placeholder="接口名称"
            />
          </a-form-item>
          <a-form-item label="接口编码">
            <a-input
              v-model="subQueryParam.interfaceCode"
              placeholder="接口编码"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <DataGrid
        ref="subList"
        type="sub"
        :url="url"
        :columns="subColumns"
        :queryParam="subQueryParam"
        rowKey="uuid"
        showPagination="auto"
        :showRowSelect="false"
      >
        <span slot="renderType" slot-scope="{ text, record }">
          {{ text | typeStr }}
        </span>
        <template slot="renderStatus" slot-scope="{ text, record }">
          <div class="flex justify-center align-center">
            <div
              class="dot-icon blue"
              v-if="text == 'intetface_status.01'"
            ></div>
            <div
              class="dot-icon green"
              v-else-if="text == 'intetface_status.02'"
            ></div>
            <div
              class="dot-icon red"
              v-else="text == 'intetface_status.03'"
            ></div>
            <span>{{ text | statusStr }}</span>
          </div>
        </template>
        <span slot="renderFormVersion" slot-scope="{ text, record }">
          <a-tag v-if="record.version" :color="'geekblue'">
            {{ "V:" + record.version }}
          </a-tag>
        </span>
        <span slot="renderAction" slot-scope="{ text, record }">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <span class="action-margin"></span>
            <a @click="handleDelSub(record)" class="action-delete">{{
              $ct("delete", "删除")
            }}</a>
            <span class="action-margin"></span>
            <a-dropdown>
              <a class="ant-dropdown-link">
                {{ $ct("more", "更多") }}
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="handlePreview(record)">预览接口</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="exportJSON(record)">{{
                    $ct("exportData", "导出数据")
                  }}</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="handleCopy(record)">复制接口</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
      </DataGrid>
      <card-selection
        ref="cardModal"
        :visible="cardVisible"
        @click="openPage"
        @cancel="() => (cardVisible = false)"
      />
      <!--静态数据-->
      <design-form
        ref="designModal"
        @cancel="handleCancelEdit"
        @ok="handleOkEdit"
        :formType="formType"
        :visibleDesign="visibleDesign"
        :isEdit="isEdit"
      />
      <!--api接口数据-->
      <apiDataEdit
        ref="apiDataModal"
        @cancel="handleCancelEdit"
        @ok="handleOkEdit"
        :visibleDesign="apiDataVisible"
        :isEdit="isEdit"
      />
      <!--数据库数据-->
      <databaseDataEdit
        ref="dataBaseDataModal"
        :visible="dataBaseDataVisible"
        @cancel="handleCancelEdit"
        @ok="handleOkEdit"
        :isEdit="isEdit"
      >
      </databaseDataEdit>
      <!-- 导入文件 -->
      <web-upload
        ref="webUploadModal"
        :visible="visibleFile"
        url="/system/sysInterfaceManagement/importJson"
        @cancel="() => (visibleFile = false)"
        @ok="importReportJson"
      />
      <!--数据预览-->
      <previewModal
        ref="previewModal"
        :visible="previewVisible"
        :model="mdl"
        @cancel="
          () => {
            (previewVisible = false), (mdl = {});
          }
        "
        @ok="
          () => {
            previewVisible = false;
          }
        "
      >
      </previewModal>
      <!--版本管理-->
      <versionForm
        ref="versionForm"
        :visible="visibleVersion"
        :loading="confirmLoadingVersion"
        :model="mdlVersion"
        @cancel="handleCancelVersion()"
        @ok="handleOkVersion"
        @refresh="refreshTable"
      ></versionForm>
    </div>
  </div>
</template>
<script>
import { baseUrl } from "@/services/baseUrl.js";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { TreeGrid, DataGrid, TableClassify } from "@/components";
import { treeGridMixin } from "@/mixins/treeGridMixin";
import cardSelection from "./cardSelection.vue";
import designForm from "./design.vue";
import apiDataEdit from "./apiDataEdit.vue";
import { getToken } from "@/utils/TopVUI";
import AInputSearch from "ant-design-vue/es/input/Search";
import Vue from "vue";
import webUpload from "./webupload.vue";
import previewModal from "./preview.vue";
import databaseDataEdit from "./databaseDataEdit.vue";
import versionForm from "./version.vue";

export default {
  mixins: [treeGridMixin],
  components: {
    AInputSearch,
    TreeGrid,
    cardSelection,
    DataGrid,
    designForm,
    TableClassify,
    webUpload,
    apiDataEdit,
    previewModal,
    databaseDataEdit,
    versionForm,
  },
  filters: {
    typeStr(val) {
      switch (val) {
        case "intetface_type.01":
          return "静态数据";
        case "intetface_type.02":
          return "API接口数据";
        case "intetface_type.03":
          return "SQL数据库数据";
        case "intetface_type.04":
          return "WebSocket";
      }
    },
    statusStr(val) {
      switch (val) {
        case "intetface_status.01":
          return "开发中";
        case "intetface_status.02":
          return "已完成";
        case "intetface_status.03":
          return "需修改";
      }
    },
  },
  data() {
    return {
      designTimeString: "1",
      templateTimeString: "2",
      key: "1",
      subColumns: [
        {
          title: "接口名称",
          dataIndex: "interfaceName",
          width: 100,
        },
        {
          title: "接口编码",
          dataIndex: "interfaceCode",
          width: 100,
        },
        {
          title: "接口类型",
          dataIndex: "interfaceType",
          width: 100,
          scopedSlots: {
            customRender: "renderType",
          },
        },
        {
          title: "状态",
          align: "center",
          dataIndex: "interfaceStatus",
          langCode: "interfaceStatus",
          width: 80,
          scopedSlots: {
            customRender: "renderStatus",
          },
        },
        {
          title: "排序",
          width: 80,
          align: "center",
          dataIndex: "interfaceSort",
        },
        {
          title: "操作",
          align: "center",
          dataIndex: "action",
          width: 200,
          scopedSlots: {
            customRender: "renderAction",
          },
          fixed: "right",
        },
      ],
      masterVisible: false,
      subVisible: false,
      subConfirmLoading: false,
      visibleVersion: false,
      confirmLoadingVersion: false,
      mdlVersion: null,
      masterMdl: null,
      subMdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      subQueryParam: {
        interfaceType: "",
        interfaceCode: "",
        interfaceName: "",
      },
      url: {
        masterList: "/system/sysInterfaceClassification/selectAll",
        subList: "/system/sysInterfaceManagement/getPageSet",
        subSave: "/system/sysInterfaceManagement/save",
        subUpdate: "/system/sysInterfaceManagement/update",
        subDelete: "/system/sysInterfaceManagement/deleteBatch",
        importExcelUrl: "/system/sysInterfaceManagement/importFormJson",
      },
      parameter: {
        father: {
          levelId: 1,
        },
        children: {},
      },
      visibleDesign: false,
      cardVisible: false,
      cardType: "",
      formType: "",
      isEdit: false,
      confirmLoading: false,
      masterConfirmLoading: false,
      classifyData: [],
      classifyTitle: "接口分类",
      masterListKey: "",
      mdl: {},
      visibleFile: false,
      apiDataVisible: false,
      previewVisible: false,
      dataBaseDataVisible: false,
    };
  },
  activated() {},
  mounted() {
    this.getClassifyData();
  },
  methods: {
    //编辑处理
    handleEdit(e) {
      this.isEdit = true;
      this.$post("/system/sysInterfaceManagement/getDetailByUuid", {
        uuid: e.uuid,
      }).then((res) => {
        if (res.statusCode === 200) {
          if (e.interfaceType === "intetface_type.01") {
            //静态数据
            this.visibleDesign = true;
            this.$refs.designModal.model = res.data;
            this.$refs.designModal.currentIndex = 0;
          } else if (e.interfaceType === "intetface_type.02") {
            //api接口数据
            this.apiDataVisible = true;
            this.$refs.apiDataModal.model = res.data;
            this.$refs.apiDataModal.currentIndex = 0;
          } else if (e.interfaceType === "intetface_type.03") {
            //sql数据
            this.dataBaseDataVisible = true;
            this.$refs.dataBaseDataModal.model = res.data;
            this.$refs.dataBaseDataModal.currentIndex = 0;
          }
        }
      });
    },
    // 新增 打开卡片对话框
    openCardSelection(type, title) {
      this.cardType = type;
      this.cardVisible = true;
      this.$refs.cardModal.title = title;
    },
    // 打开新增页面
    openPage(key) {
      if (key === "static") {
        this.$refs.designModal.model = { interfaceType: "intetface_type.01" };
        this.visibleDesign = true;
        this.$refs.designModal.currentIndex = 0;
      } else if (key === "apiData") {
        this.$refs.apiDataModal.model = { interfaceType: "intetface_type.02" };
        this.apiDataVisible = true;
        this.$refs.apiDataModal.currentIndex = 0;
      } else if (key === "dataBaseData") {
        this.dataBaseDataVisible = true;
        this.$refs.dataBaseDataModal.currentIndex = 0;
        this.$refs.dataBaseDataModal.model = {
          interfaceType: "intetface_type.03",
        };
      }
      this.cardVisible = false;
      this.formType = key;
      this.isEdit = false;
    },
    //点击导入处理
    importReportFile() {
      this.$refs.webUploadModal.add();
      this.visibleFile = true;
    },
    //导入确定回调
    importReportJson() {
      this.visibleFile = false;
      this.$refs.subList.refresh(true);
    },
    //导出数据
    exportJSON(record) {
      const that = this;
      that.$confirm({
        title: "操作提示",
        content: "确定要导出该接口吗?",
        okText: "确定",
        cancelText: "取消",
        closable: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          window.location.href =
            baseUrl +
            "/system/sysInterfaceManagement/exportJson?&uuid=" +
            record.uuid +
            "&token=" +
            Vue.ls.get(ACCESS_TOKEN);
        },
      });
    },
    //跳转到预览页面
    handlePreview(record) {
      this.$post("/system/sysInterfaceManagement/getDetailByUuid", {
        uuid: record.uuid,
      }).then((detailRes) => {
        if (detailRes.statusCode === 200) {
          this.$post("/system/sysInterfaceManagement/invokeInterface", {
            uuid: record.uuid,
          }).then((res) => {
            if (res.statusCode === 200) {
              this.previewVisible = true;
              this.$nextTick(() => {
                try {
                  const fun = eval(JSON.parse(detailRes.data.dataFilter));
                  const monaco = this.$refs.previewModal.$refs.monaco;
                  if (record.interfaceType === "intetface_type.01") {
                    monaco.setValue(JSON.parse(res.data));
                  } else if (record.interfaceType === "intetface_type.02") {
                    res.data = JSON.parse(res.data);
                    monaco.setValue(
                      JSON.stringify(fun(res.data), null, 2),
                      "json",
                      {}
                    );
                  } else if (record.interfaceType === "intetface_type.03") {
                    monaco.setValue(
                      JSON.stringify(fun(res), null, 2),
                      "json",
                      {}
                    );
                  }
                } catch (e) {
                  console.log(e);
                }
              });
            } else {
              this.$message.error(res.message, 1.5);
            }
          });
        }
      });
    },
    //版本管理
    versionManage() {
      this.visibleVersion = true;
      this.mdlVersion = e.modelKey;
      if (this.$refs.versionForm)
        this.$refs.versionForm.refreshList(e.modelKey);
    },
    // 关闭版本弹窗
    handleCancelVersion() {
      this.visibleVersion = false;
    },
    // 确定主要版本
    handleOkVersion() {
      this.confirmLoadingVersion = true;
      this.visibleVersion = false;
      this.$refs.subList.refresh(true);
    },
    // 刷新数据表格
    refreshTable() {
      this.$refs.subList.refresh(true);
    },
    masterRowClick(e) {
      this.subQueryParam.classificationUuid = e[0];
      this.masterListKey = e[0];
      this.$refs.subList.rows = null;
      this.$refs.subList.refresh();
    },
    getClassifyData() {
      this.masterConfirmLoading = true;
      this.$post(this.url.masterList, {}).then((res) => {
        if (res) {
          this.classifyData = res.data;
          this.masterConfirmLoading = false;
        }
      });
    },
    onExpand() {
      console.log("Trigger Expand");
    },
    handleCancelEdit(type) {
      if (type == "staticData") {
        this.visibleDesign = false;
        this.$refs.designModal.model = null;
      } else if (type == "apiData") {
        this.apiDataVisible = false;
        this.$refs.apiDataModal.model = null;
      } else if (type == "dataBaseData") {
        this.dataBaseDataVisible = false;
        this.$refs.dataBaseDataModal.model = null;
      }
    },
    handleOkEdit(type) {
      if (type == "staticData") {
        this.visibleDesign = false;
        this.$refs.designModal.model = null;
      } else if (type == "apiData") {
        this.apiDataVisible = false;
        this.$refs.apiDataModal.model = null;
      } else if (type == "dataBaseData") {
        this.dataBaseDataVisible = false;
        this.$refs.dataBaseDataModal.model = null;
      }
      this.$refs.subList.refresh();
    },
    // 设计
    handleViewDesign(e) {
      if (e.type === "createPage") {
        this.$refs.designModal.stepList.splice(3, 1);
      }
      this.formType = e.type;
      this.$refs.designModal.getData(e);
      this.visibleDesign = true;
      this.isEdit = true;
    },
    handleDelSub(record, type) {
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          that
            .$post(that.url.subDelete, {
              uuid: record.uuid,
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                that.$refs.subList.refresh();
              } else {
                that.$message.error(res.message);
              }
            });
        },
      });
    },
    resetSearchForm() {
      this.subQueryParam = {
        classificationUuid: this.masterListKey,
      };
      this.$refs.subList.refresh(true);
    },
    // 复制接口
    handleCopy(record) {
      const that = this;
      that.$confirm({
        title: "操作提示",
        content: "确定要复制该接口吗?",
        okText: "确定",
        cancelText: "取消",
        closable: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          that
            .$post(
              "/system/sysInterfaceManagement/copySysInterfaceManagement",
              {
                uuid: record.uuid,
              }
            )
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success(res.message, 1.5);
                that.$refs.subList.refresh();
              } else {
                that.$message.error(res.message, 1.5);
              }
            });
        },
      });
    },
  },
};
</script>

<style scoped lang="less">
.dot-icon {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 5px;
}

.dot-icon.blue {
  background-color: dodgerblue;
}

.dot-icon.green {
  background-color: forestgreen;
}

.dot-icon.red {
  background-color: red;
}

.page-common-layout .page-common-left + .page-common-content {
  max-width: unset !important;
}
</style>
